<template>
	<view>
		<navbar></navbar>
		<!-- #ifndef MP -->
		<view class="register-container">
			<view class="logo-box">
				<view class="img"></view>
				<!-- <view class="name">{{ appName }}</view> -->
			</view>
			<view class="invite-box" v-if="hasInviteCode && canIUseInvite">
				<view class="label">推荐人邀请码</view>
				<view class="code">{{inviteCode}}</view>
			</view>
			<view class="register-box">
				<view class="form-item">
					<view class="label">手机号</view>
					<view class="form-input">
						<input v-model="mobile" type="number" placeholder="请输入手机号" />
					</view>
				</view>
				<view class="form-item">
					<view class="label">验证码</view>
					<view class="form-input">
						<input v-model="validate" placeholder="请输入验证码" maxlength="6" />
						<send-code :mobile="mobile" ref="sendCode" @checkphone="checkPhone"></send-code>
					</view>
				</view>
				<view class="form-item">
					<view class="label">密码</view>
					<view class="form-input">
						<input v-if="showPwd" v-model="pwd" type="text" placeholder="请输入密码(至少8位且含字母/数字)" />
						<input v-else v-model="pwd" type="password" placeholder="请输入密码(至少8位且含字母/数字)" />
						<view class="pwd-eye" @click="changePwdVisible('showPwd')"><i class="dy-iconfont"
								:class="[{'icon-show':showPwd},{'icon-hide':!showPwd}]"></i></view>
					</view>
				</view>
				<view class="form-item">
					<view class="label">确认密码</view>
					<view class="form-input">
						<input v-if="showConfirmPwd" v-model="confirmPwd" type="text" placeholder="再次确认密码" />
						<input v-else v-model="confirmPwd" type="password" placeholder="再次确认密码" />
						<view class="pwd-eye" @click="changePwdVisible('showConfirmPwd')"><i class="dy-iconfont"
								:class="[{'icon-show':showConfirmPwd},{'icon-hide':!showConfirmPwd}]"></i></view>
					</view>
				</view>
				<view class="form-item" v-if="!hasInviteCode && canIUseInvite">
					<view class="label">邀请码</view>
					<view class="form-input">
						<input v-model="inviteCode" placeholder="请输入邀请码（选填）" />
					</view>
				</view>
			</view>
			<button class="register-btn" @click="submit()">注册</button>
      <view v-if="canIUseAgreement" class="m-top20">
        <label class="f-24 dis-flex" @click="agreementChecked = !agreementChecked">
          <text v-if="!agreementChecked" class="dy-iconfont icon-weigouxuan"></text>
          <text v-else class="dy-iconfont icon-gouxuan" style="color:#000;"></text>
          <!-- <text class="m-left10 col-9">注册即代表您已阅读并同意{{ appName }}的<text v-if="1 == user_agreement_status" class="col-m" @click.stop="showRegisterAgreement('user_agreement', user_agreement_title)">《{{ user_agreement_title }}》</text>{{ connectText }}<text v-if="privacy_agreement_status" class="col-m" @click.stop="showRegisterAgreement('privacy_agreement', privacy_agreement_title)">《{{ privacy_agreement_title }}》</text></text> -->
          <text class="m-left10 col-9">已阅读并同意<text v-if="1 == user_agreement_status" class="col-m" @click.stop="showRegisterAgreement('user_agreement', user_agreement_title)">《{{ user_agreement_title }}》</text>{{ connectText }}<text v-if="privacy_agreement_status" class="col-m" @click.stop="showRegisterAgreement('privacy_agreement', privacy_agreement_title)">《{{ privacy_agreement_title }}》</text></text>
        </label>
      </view>
			<view class="link-view center">
				<view @click="goLogin()">
					已有账号？<text class="dark">立即登录</text>
				</view>
			</view>
			<!-- #ifdef APP-PLUS -->
			<view class="copyright">
				<view>@2022 king艺术</view>
				<view><image mode="widthFix" class="beian" src="https://qiniu.wiod.cn/alc/777.png"></image>
				<a target="_blank">浙公网安备 33010802012379号</a></view>
				<!-- <image mode="widthFix" src="https://qiniu.wiod.cn/alc/599.png"></image> -->
			</view>
			<!-- #endif -->
			
		</view>
		<view class="pop" v-if="wxPop">
			<image src="/static/images/wxpop.png" mode=""></image>
		</view>
		<!-- #endif -->

		<!-- #ifdef MP -->
		<view class="container">
			<view class="wechatapp">
				<view class="header">
					<open-data class="" type="userAvatarUrl"></open-data>
				</view>
			</view>
			<view class="auth-title">申请获取以下权限</view>
			<view class="auth-subtitle">获得你的公开信息（昵称、头像等）</view>
			<view class="login-btn">
				<button v-if="canIUseGetUserProfile" class="btn-normal" @tap.stop.prevent="getUserProfile">授权登录</button>
				<button v-else class="btn-normal" openType="getUserInfo" lang="zh_CN"
					@getuserinfo="getUserInfo">授权登录</button>
			</view>
			<view class="no-login-btn">
				<button class="btn-normal" @tap.stop.prevent="onNotLogin">暂不登录</button>
			</view>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import siteinfo from '@/siteinfo.js';
	// #ifndef MP
	import {
		isPhone,
		isPwd,
		isPositiveInteger,
		isWeixin
	} from "@/utils/verify.js"
	import navbar from "@/components/navbar/navbar";
	const app = getApp();
	export default {
		components: {
			navbar
		},
		data() {
			return {
				hasInviteCode: false, //是否连接中已存在邀请码
				showPwd: false, //密码是否明文
				showConfirmPwd: false, //确认密码是否明文

				mobile: '',
				validate: '',
				pwd: '',
				confirmPwd: '',
				inviteCode: '', //邀请码
				wxPop:false,
				canIUseInvite: false,
				appName: siteinfo.name,
				user_agreement_title: '用户注册协议',
        user_agreement_status: 0, // 有注册协议
		privacy_agreement_title: '隐私政策',
        privacy_agreement_status: 0, // 有隐私协议
        agreementChecked: false,
			}
		},
		onLoad(options) {
      // 微信环境下不执行
	  var ua = window.navigator.userAgent.toLowerCase();
	  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
	  		  this.wxPop=true
	  }
      if(isWeixin()){
        return;
      }

			let inviteCode = options.invite_code; //获取链接中携带的邀请码
			if (inviteCode) {
				this.setData({
					hasInviteCode: true,
					inviteCode: inviteCode
				});
			}
			this.canIUseInvite = !isWeixin();
			// 请求协议
      this.requestAgreementStatus();
		},
    computed: {
      canIUseAgreement: function () {
        return 1 == this.user_agreement_status || 1 == this.privacy_agreement_status;
      },
      connectText: function () {
        return (1 == this.user_agreement_status && 1 == this.privacy_agreement_status) ? '和' : '';
      }
    },
		methods: {
      requestAgreementStatus() {
        app._get('user/registerrulestatus', null, (res) => {
            this.privacy_agreement_status = res.data.privacy_agreement_status;
            this.user_agreement_status = res.data.user_agreement_status;
        });
      },
			validateData() {
				if (this.mobile == "") {
					app.showToast('请输入手机号');
					return false;
				}
				if (!isPhone(this.mobile)) {
					app.showToast('手机号格式不正确');
					return false;
				}
				if (this.validate == "") {
					app.showToast('请输入验证码');
					return false;
				}
				if (!isPositiveInteger(this.validate)) {
					app.showToast('验证码不正确');
					return false;
				}
				if (this.pwd == "") {
					app.showToast('请输入密码');
					return false;
				}
				if (!isPwd(this.pwd)) {
					app.showToast('密码格式不正确(至少8位且含字母/数字)');
					return false;
				}
				if (this.confirmPwd == "") {
					app.showToast('请输入确认密码');
					return false;
				}
				if (this.confirmPwd !== this.pwd) {
					app.showToast('两次密码输入不一致');
					return false;
				}
				return true;
			},
			changePwdVisible(name) {
				this[name] = !this[name];
			},
			/**
			 * 授权成功 跳转回原页面
			 */
			onNavigateBack() {
				app.navigationBack();
			},
			// 发送验证码前校验手机号
			checkPhone() {
				if (!isPhone(this.mobile)) {
					app.showToast('手机号格式不正确');
					return;
				}
				let params = {
					phone: this.mobile,
				}
				app._get('user/checkPhoneRegister', params, res => { // success
					// "has_reg": 0   //0:未注册 1:已注册
					let hasReg = res.data.has_reg;
					if (hasReg == 0) {
						// 通过校验
						this.$refs.sendCode.checkPhoneOk();
					} else {
						app.showToast('该手机号已注册！');
					}
				}, false, () => { //complete
					uni.hideLoading();
				});
			},


			// 注册
			submit() {
				var valid = this.validateData();

				// 校验不通过
				if (!valid) {
					return false;
				}

        if (this.canIUseAgreement && !this.agreementChecked) {
			var message = '请先阅读并勾选';
			if (1 == this.user_agreement_status) {
				message += `《${this.user_agreement_title}》`
			}
			message += this.connectText;
			if (1 == this.privacy_agreement_status) {
				message += `《${this.privacy_agreement_title}》`
			}
          app.showError(message);
          return false;
        }

				let params = {
					from: 'h5',
					is_wx: 0,
					nickName: this.mobile,
					smscode: this.validate,
					password: this.pwd, //密码
					confirmPassword: this.confirmPwd, //确认密码
					inviteCode: this.inviteCode,
					wxapp_id: app.globalData.wxapp_id
				}

				app._post_form('user/reg', params, result => {
					app.showSuccess('注册成功', this.goLogin)
				}, false, () => {
					uni.hideLoading();
				});
			},
			// 跳转到登陆页面
			goLogin() {
				let lastPage = app.lastPage()
				//判断上一页是否是登录页面，否则直接跳转到登录页
				if (lastPage && lastPage.route.indexOf("pages/login/login") == 0) {
					this.onNavigateBack();
				} else {
					uni.redirectTo({
						url: '/pages/login/login'
					});
				}
			},
			showRegisterAgreement(type, title) {
				uni.navigateTo({
					url:`./agreement?type=${type}&title=${title}`
				})
			}
		}
	}
	// #endif

	// #ifdef MP
	const app = getApp();
	export default {
		data() {
			return {
				canIUseGetUserProfile: false,
				appName: siteinfo.name,
			}
		},
		onLoad() {
			if (uni.getUserProfile) {
				this.canIUseGetUserProfile = true;
			}
		},
		methods: {
			getUserProfile(e) {
				// 推荐使用uni.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
				// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
				uni.getUserProfile({
					desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						let _this = this;
						app.getUserProfile(res, () => {
							// 跳转回原页面
							_this.onNavigateBack();
						});
					}
				})
			},
			/**
			 * 授权登录
			 */
			getUserInfo(e) {
				let _this = this;
				app.getUserInfo(e, () => {
					// 跳转回原页面
					_this.onNavigateBack();
				});
			},
			/**
			 * 暂不登录
			 */
			onNotLogin() {
				let _this = this;
				// 跳转回原页面
				_this.onNavigateBack();
			},
			/**
			 * 授权成功 跳转回原页面
			 */
			onNavigateBack() {
				uni.navigateBack();
			}
		}
	}
	// #endif
</script>

<style lang="scss" scoped>
	@import '../../utils/login.scss';
	.copyright {
		text-align: center;
		margin: 80rpx 0 40rpx 0;
		font-size: 24rpx;
	}
	.copyright image {
		width: 100rpx;
		margin: 20rpx auto 0;
	}
	.copyright .beian{
		width:26rpx;
		margin-right: 10px;
	}
	.pop{
		position: fixed;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		// background: rgba(0, 0, 0, 0.1);
		z-index: 10001;
	}
	.pop image{
		width: 100%;
		height: 100%;
	}
</style>
